# add update time to meta
import os
import re
import time

# 给文章插入image_url标签
def insert_image_url(md_file):
    path_pre = '/Users/rustfisher/Desktop/ws/wiki-ws/mk-android-wiki-proj/mk-an-wiki/docs/'
    pattern = re.compile(r': (.*?).md', re.S)
    filepath_list = []  # md files 
    with open(md_file) as md:
        for line in md.readlines():
            line = str(line)

            cur_urls = re.findall(pattern, line)
            if len(cur_urls) > 0:
                if cur_urls[0] == '/':
                    continue
                if not cur_urls[0].startswith("android"):
                    continue
                filepath_list.append(path_pre + cur_urls[0] + '.md')

    print('md files count: ', len(filepath_list))

    err_filepath_list = []
    for md_file in filepath_list:
        if not os.path.exists(md_file):
            err_filepath_list.append(md_file)
            continue
        has_img_url = False
        with open(md_file) as md:
            for line in md.readlines():
                line = str(line)
                if line.startswith("image_url: "):
                    has_img_url = True
                    continue

        if not has_img_url:
            # print('need image url', md_file)
            meta_add_image_url(md_file)


def meta_add_image_url(md_file):
    time1 = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime()) 
    tmp_content = []
    with open(md_file, "r") as f:
        tmp_content = f.readlines()
    tmp_content.insert(2, 'image_url: _media/cover/as-logo-700.png\n')
    with open(md_file, "w") as f:
        f.writelines(tmp_content)


if __name__ == '__main__':
    print('go ----- ')
    insert_image_url('/Users/rustfisher/Desktop/ws/wiki-ws/mk-android-wiki-proj/mk-an-wiki/mkdocs.yml')
